/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package persistence;

import entityBeans.Site;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import entityBeans.Localityelement;
import java.util.ArrayList;
import java.util.List;
import persistence.exceptions.NonexistentEntityException;

/**
 *
 * @author allankv
 */
public class SiteJpaController {

    public SiteJpaController() {
        emf = Persistence.createEntityManagerFactory("bdd-javaPU");
    }
    private EntityManagerFactory emf = null;

    public EntityManager getEntityManager() {
        return emf.createEntityManager();
    }

    public Site save(Site site) {
        Site aux = findSite(site.getSite());
        if(aux==null)
            return create(site);
        else
            return aux;
    }

    public Site create(Site site) {
        Site r = null;
        if (site.getLocalityelementList() == null) {
            site.setLocalityelementList(new ArrayList<Localityelement>());
        }
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            List<Localityelement> attachedLocalityelementList = new ArrayList<Localityelement>();
            for (Localityelement localityelementListLocalityelementToAttach : site.getLocalityelementList()) {
                localityelementListLocalityelementToAttach = em.getReference(localityelementListLocalityelementToAttach.getClass(), localityelementListLocalityelementToAttach.getIdlocalityelement());
                attachedLocalityelementList.add(localityelementListLocalityelementToAttach);
            }
            site.setLocalityelementList(attachedLocalityelementList);
            r = em.merge(site);
            for (Localityelement localityelementListLocalityelement : site.getLocalityelementList()) {
                Site oldSiteOfLocalityelementListLocalityelement = localityelementListLocalityelement.getSite();
                localityelementListLocalityelement.setSite(site);
                localityelementListLocalityelement = em.merge(localityelementListLocalityelement);
                if (oldSiteOfLocalityelementListLocalityelement != null) {
                    oldSiteOfLocalityelementListLocalityelement.getLocalityelementList().remove(localityelementListLocalityelement);
                    oldSiteOfLocalityelementListLocalityelement = em.merge(oldSiteOfLocalityelementListLocalityelement);
                }
            }
            em.getTransaction().commit();
        } finally {
            if (em != null) {
                em.close();
            }
        }
        return r;
    }

    public void edit(Site site) throws NonexistentEntityException, Exception {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Site persistentSite = em.find(Site.class, site.getIdsite());
            List<Localityelement> localityelementListOld = persistentSite.getLocalityelementList();
            List<Localityelement> localityelementListNew = site.getLocalityelementList();
            List<Localityelement> attachedLocalityelementListNew = new ArrayList<Localityelement>();
            for (Localityelement localityelementListNewLocalityelementToAttach : localityelementListNew) {
                localityelementListNewLocalityelementToAttach = em.getReference(localityelementListNewLocalityelementToAttach.getClass(), localityelementListNewLocalityelementToAttach.getIdlocalityelement());
                attachedLocalityelementListNew.add(localityelementListNewLocalityelementToAttach);
            }
            localityelementListNew = attachedLocalityelementListNew;
            site.setLocalityelementList(localityelementListNew);
            site = em.merge(site);
            for (Localityelement localityelementListOldLocalityelement : localityelementListOld) {
                if (!localityelementListNew.contains(localityelementListOldLocalityelement)) {
                    localityelementListOldLocalityelement.setSite(null);
                    localityelementListOldLocalityelement = em.merge(localityelementListOldLocalityelement);
                }
            }
            for (Localityelement localityelementListNewLocalityelement : localityelementListNew) {
                if (!localityelementListOld.contains(localityelementListNewLocalityelement)) {
                    Site oldSiteOfLocalityelementListNewLocalityelement = localityelementListNewLocalityelement.getSite();
                    localityelementListNewLocalityelement.setSite(site);
                    localityelementListNewLocalityelement = em.merge(localityelementListNewLocalityelement);
                    if (oldSiteOfLocalityelementListNewLocalityelement != null && !oldSiteOfLocalityelementListNewLocalityelement.equals(site)) {
                        oldSiteOfLocalityelementListNewLocalityelement.getLocalityelementList().remove(localityelementListNewLocalityelement);
                        oldSiteOfLocalityelementListNewLocalityelement = em.merge(oldSiteOfLocalityelementListNewLocalityelement);
                    }
                }
            }
            em.getTransaction().commit();
        } catch (Exception ex) {
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0) {
                Integer id = site.getIdsite();
                if (findSite(id) == null) {
                    throw new NonexistentEntityException("The site with id " + id + " no longer exists.");
                }
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void destroy(Integer id) throws NonexistentEntityException {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Site site;
            try {
                site = em.getReference(Site.class, id);
                site.getIdsite();
            } catch (EntityNotFoundException enfe) {
                throw new NonexistentEntityException("The site with id " + id + " no longer exists.", enfe);
            }
            List<Localityelement> localityelementList = site.getLocalityelementList();
            for (Localityelement localityelementListLocalityelement : localityelementList) {
                localityelementListLocalityelement.setSite(null);
                localityelementListLocalityelement = em.merge(localityelementListLocalityelement);
            }
            em.remove(site);
            em.getTransaction().commit();
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public List<Site> findSiteEntities() {
        return findSiteEntities(true, -1, -1);
    }

    public List<Site> findSiteEntities(int maxResults, int firstResult) {
        return findSiteEntities(false, maxResults, firstResult);
    }

    private List<Site> findSiteEntities(boolean all, int maxResults, int firstResult) {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            cq.select(cq.from(Site.class));
            Query q = em.createQuery(cq);
            if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } finally {
            em.close();
        }
    }

    public Site findSite(String q) {
        Query query= getEntityManager().createNamedQuery("Site.findBySite");
        query.setParameter("site",q);

        return query.getResultList().isEmpty()?null:(Site)query.getResultList().get(0);
    }

    public Site findSite(Integer id) {
        EntityManager em = getEntityManager();
        try {
            return em.find(Site.class, id);
        } finally {
            em.close();
        }
    }

    public int getSiteCount() {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            Root<Site> rt = cq.from(Site.class);
            cq.select(em.getCriteriaBuilder().count(rt));
            Query q = em.createQuery(cq);
            return ((Long) q.getSingleResult()).intValue();
        } finally {
            em.close();
        }
    }

}
